package edu.clarkson.ee368.spring2012.coreservices;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


@WebServlet("/messages")
public class MessageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private DocumentBuilder documentBuilder;
	
	@EJB
	private NotificationService notificationService;
	
	public MessageServlet() {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			this.documentBuilder = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		Document doc = null;
		try {
			doc = documentBuilder.parse(req.getInputStream());
		}
		catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Node commandNode = doc.getFirstChild();
		String command = commandNode.getNodeName();
		if ("send-message".equals(command)) {
			long accountID = Long.parseLong(commandNode.getAttributes().getNamedItem("account-id").getNodeValue());
			String hostedAppName = commandNode.getAttributes().getNamedItem("application").getNodeValue();
			Map<String,String> data = new HashMap<String,String>();
			NodeList childNodeList = commandNode.getChildNodes();
			for (int i = 0; i < childNodeList.getLength(); i++) {
				Node childNode = childNodeList.item(i);
				if (childNode.getNodeName().equals("parameter")) {
					String paramName = childNode.getAttributes().getNamedItem("name").getNodeValue();
					String paramValue = childNode.getAttributes().getNamedItem("value").getNodeValue();
					data.put(paramName, paramValue);
				}
			}
			notificationService.sendMessage(hostedAppName, accountID, data);
			resp.setStatus(200);
		}
	}
	
	

}
